<template>
	<div class="select">
		<van-field
			class="iptBox"
			is-link
			:readonly="true"
			clickable
			:required="required"
			:name="name"
			@focus="selectArea"
			v-model="value"
			:label="label"
			placeholder="请选择"
			:rules="[{ required: required }]"
		/>
		<van-popup
			:close-on-click-overlay="false"
			v-model="showAddressSelector"
			@close="closeAreaPop"
			position="bottom"
			:style="{ height: '70%' }"
		>
			<!-- 选择器主体 -->
			<div class="page-main">
				<!-- 操作区域 包含取消和确定 -->
				<div class="main-operate">
					<div class="title-txt" @click.stop="handleCancel">取消</div>
					<div class="title-txt" @click.stop="handleSubmit">确定</div>
				</div>
				<!-- 已选择的地址信息 -->
				<div class="main-select" :class="[selectAreaLevelLimit == 3 ? 'w33_percent' : '']">
					<div
						v-if="showIndex == 0 || provinceObj.name"
						:class="showIndex == 0 ? 'select' : ''"
						@click="anewSelect(0)"
					>
						{{ provinceObj.name || '请选择' }}
					</div>
					<div
						v-if="showIndex == 1 || cityObj.name"
						:class="showIndex == 1 ? 'select' : ''"
						@click="anewSelect(1)"
					>
						{{ cityObj.name || '请选择' }}
					</div>
					<div
						v-if="showIndex == 2 || areaObj.name"
						:class="showIndex == 2 ? 'select' : ''"
						@click="anewSelect(2)"
					>
						{{ areaObj.name || '请选择' }}
					</div>
					<div
						v-if="showIndex == 3 || streetObj.name"
						:class="showIndex == 3 ? 'select' : ''"
						@click="anewSelect(3)"
					>
						{{ streetObj.name || '请选择' }}
					</div>
					<div
						v-if="showIndex == 4 || villageObj.name"
						:class="showIndex == 4 ? 'select' : ''"
						@click="anewSelect(4)"
					>
						{{ villageObj.name || '请选择' }}
					</div>
				</div>
				<!-- 待选择的地址信息 -->
				<div class="main-list">
					<van-loading
						style="
							position: absolute;
							left: 50%;
							top: 50%;
							transform: translate(-50%, -50%);
						"
						v-if="isLoading"
					/>
					<div v-if="showIndex == 0">
						<div
							class="list-box"
							:class="provinceObj.id == item.id ? 'active' : ''"
							@click="handleSelectAddress(0, item)"
							v-for="item in provinceData"
							:key="item.id"
						>
							<div>{{ item.name || '' }}</div>
						</div>
					</div>
					<div v-if="showIndex == 1">
						<div
							class="list-box"
							:class="cityObj.id == item.id ? 'active' : ''"
							@click="handleSelectAddress(1, item)"
							v-for="item in cityData"
							:key="item.id"
						>
							<div>{{ item.name || '' }}</div>
						</div>
					</div>
					<div v-if="showIndex == 2">
						<div
							class="list-box"
							:class="areaObj.id == item.id ? 'active' : ''"
							@click="handleSelectAddress(2, item)"
							v-for="item in areaData"
							:key="item.id"
						>
							<div>{{ item.name || '' }}</div>
						</div>
					</div>
					<div v-if="showIndex == 3">
						<div
							class="list-box"
							:class="streetObj.id == item.id ? 'active' : ''"
							@click="handleSelectAddress(3, item)"
							v-for="item in streetsData"
							:key="item.id"
						>
							<div>{{ item.name || '' }}</div>
						</div>
					</div>
					<div v-if="showIndex == 4">
						<div
							class="list-box"
							:class="villageObj.id == item.id ? 'active' : ''"
							@click="handleSelectAddress(4, item)"
							v-for="item in villagesData"
							:key="item.id"
						>
							<div>{{ item.name || '' }}</div>
						</div>
					</div>
				</div>
			</div>
		</van-popup>
	</div>
</template>

<script>
// 自定义区划选择器-可限制选择层级、默认选择层级、回显地址
import { get_area } from '@/api/user.js'
export default {
	name: 'commonAreaByUni',
	props: {
		// 组件树回显地址对象
		areaInfoSelected: {
			type: Object,
			default: {}
		},
		// 传0-5  0 可选任意一级 1省级 2市级 3县区级 4街道/乡镇 5社区/村
		selectAreaLevelLimit: {
			type: Number,
			default: 5
		},
		// field文本框回显值-显示在外层
		value: {
			type: [String,Number],
			require: false
		},
		// label标题
		label: {
			type: String,
			require: false
		},
		// 绑定标识
		name: {
			type: String,
			require: false
		},
		// 是否必填
		required: {
			type: Boolean,
			require: false,
			default: false
		},
		// true户籍地址 false常住地址
		isRegister: {
			type: Boolean,
			require: false,
			default: false
		},
		// 是否只读
		readonly: {
			type: Boolean,
			require: false,
			default: false
		},
		// 限制默认最小回显等级 0省级 1市级 2县区级 ；必须设置默认组件树回显地址对象areaInfoSelected或者isXiaMen
		defaultLimitArea: {
			type: Number,
			require: false,
			default: -1
		}
		// 是否默认从厦门开始选择
		// isXiaMen: {
		//   type: Boolean,
		//   require: false,
		//   default: false,
		// },
	},
	data() {
		return {
      currentLastLevel:0,// 当前接口拿到的最后一级行政级别
			showAddressSelector: false,
			isLoading: false,
			showIndex: 0, // 地区显示
			provinceObj: {},
			cityObj: {},
			areaObj: {},
			streetObj: {},
			villageObj: {},
			provinceData: [], // 省级
			cityData: [], // 市级
			areaData: [], //县区
			streetsData: [], //街道
			villagesData: [] // 村、社区
		}
	},
	watch: {
		showAddressSelector(newVal, oldVal) {
			if (newVal) {
				this.getDefaultArea()
			}
		}
	},
	created() {
		this.getDefaultArea()
	},
	methods: {
		selectArea() {
			if (!this.readonly) {
				this.showAddressSelector = true
			}
		},
		getDefaultArea() {
			if (
				this.areaInfoSelected &&
				this.areaInfoSelected.provinceObj &&
				this.areaInfoSelected.provinceObj.id
			) {
				let { provinceObj, cityObj, areaObj, streetObj, villageObj } = this.areaInfoSelected
				this.provinceObj = provinceObj
				this.cityObj = cityObj
				this.areaObj = areaObj
				this.streetObj = streetObj
				this.villageObj = villageObj
				if (!cityObj.id) {
					this.handleGetMap({}, 'init')
				}
				if (cityObj.id && !areaObj.id) {
					this.handleGetMap(this.areaInfoSelected.provinceObj, 'pro')
				}
				if (areaObj.id && !streetObj.id) {
					this.handleGetMap(this.areaInfoSelected.cityObj, 'city')
				}
				if (streetObj.id && !villageObj.id) {
					this.handleGetMap(this.areaInfoSelected.areaObj, 'area')
				}
				if (villageObj.id) {
					this.handleGetMap(this.areaInfoSelected.streetObj, 'street')
				}
				// console.log("传入的this.areaInfoSelected", this.areaInfoSelected);
			} else {
				this.handleGetMap({}, 'init')
			}
		},
		closeAreaPop() {
			// this.$emit("update:showAddressSelector", false);
			this.showAddressSelector = false
		},
		//取消
		handleCancel() {
			// this.$emit("cancel");
			this.showAddressSelector = false
		},
		//确定
		handleSubmit() {
			const { provinceObj, cityObj, areaObj, streetObj, villageObj } = this
			const arr = [provinceObj, cityObj, areaObj, streetObj, villageObj]
			let fullAreaName = []
			arr.map((item) => {
				if (item.id) {
					fullAreaName.push(item.name)
				}
			})
			if (this.selectAreaLevelLimit && this.selectAreaLevelLimit != 0) {
				if (this.selectAreaLevelLimit > 0) {
					if (fullAreaName.length < this.selectAreaLevelLimit) {
						if (this.selectAreaLevelLimit == 2) {
							this.$toast.fail('地址需精确到市级')
						}
						if (this.selectAreaLevelLimit == 3) {
							this.$toast.fail( '地址需精确到县区级')
						}
						if (this.selectAreaLevelLimit == 4) {
							this.$toast.fail('地址需精确到街道/乡镇级')
						}
						if (this.selectAreaLevelLimit == 5) {
							this.$toast.fail('地址需精确到社区/村级')
						}
						return
					}
				} else {
          // 限制必须选择到最后一级
          console.log(this.currentLastLevel);
          console.log(fullAreaName.length);
          if(this.currentLastLevel != fullAreaName.length) {
            this.$toast.fail('地址需精确最后一级')
            return
          }
				}
			}
			let areaInfoObj
			if (this.isRegister) {
				areaInfoObj = {
					obj: {
						registerProvince: provinceObj.id || '',
						registerCity: cityObj.id || '',
						registerCounty: areaObj.id || '',
						registerStreet: streetObj.id || '',
						registerCommunity: villageObj.id || '',
						registerProvinceName: provinceObj.name || '',
						registerCityName: cityObj.name || '',
						registerCountyName: areaObj.name || '',
						registerStreetName: streetObj.name || '',
						registerCommunityName: villageObj.name || ''
					},
					defaultObj: {
						provinceObj,
						cityObj,
						areaObj,
						streetObj,
						villageObj
					},
					fullArea: fullAreaName.toString().replace(/,/g, '')
				}
			} else {
				areaInfoObj = {
					obj: {
						province: provinceObj.id || '',
						city: cityObj.id || '',
						county: areaObj.id || '',
						street: streetObj.id || '',
						community: villageObj.id || '',
						provinceName: provinceObj.name || '',
						cityName: cityObj.name || '',
						countyName: areaObj.name || '',
						streetName: streetObj.name || '',
						communityName: villageObj.name || ''
					},
					defaultObj: {
						provinceObj,
						cityObj,
						areaObj,
						streetObj,
						villageObj
					},
					fullArea: fullAreaName.toString().replace(/,/g, '')
				}
			}
			this.$emit('update:value', areaInfoObj.fullArea)
			this.$emit('confirm', areaInfoObj)
			this.showAddressSelector = false
		},
		//下拉选择
		anewSelect(num) {
			switch (num) {
				case 0:
					if (this.defaultLimitArea >= 0) {
						return
					}
					this.showIndex = 0
					this.cityObj = {}
					this.areaObj = {}
					this.streetObj = {}
					this.villageObj = {}
					this.cityData = []
					this.areaData = []
					this.streetsData = []
					this.villagesData = []
					this.handleGetMap({}, 'init')
					break
				case 1:
					if (this.defaultLimitArea >= 1) {
						return
					}
					this.showIndex = 1
					this.streetObj = {}
					this.villageObj = {}
					this.areaData = []
					this.streetsData = []
					this.villagesData = []
					// if (!this.areaObj.id) return;
					this.areaObj = {}
					this.handleGetMap(this.provinceObj, 'pro')
					break
				case 2:
					if (this.defaultLimitArea >= 2) {
						return
					}
					this.showIndex = 2
					this.streetsData = []
					this.villagesData = []
					this.villageObj = {}
					// if (!this.streetObj.id) return;
					this.streetObj = {}
					this.handleGetMap(this.cityObj, 'city')
					break
				case 3:
					this.showIndex = 3
					this.villagesData = []
					this.villageObj = {}
					// if (!this.villageObj.id) return;
					this.handleGetMap(this.areaObj, 'area')
					break
			}
		},
		handleGetMap(obj, type) {
			// name选择名称 type类型
			let that = this,
				data = {
					parentArea: 0
				}

			if (type !== 'init') {
				data.parentArea = obj.id
				this.isLoading = true
			}
			let areaCode
			if (obj && obj.id) {
				areaCode = obj.id
			} else {
				areaCode = '000000'
			}

			// 每次请求带上parentArea 即可请求下一级区域数据
			get_area({ areaCode }).then((res) => {
				if (res.succeed) {
					let arr = ['init', 'pro', 'city', 'area', 'street']
					let _obj = {
						init: 'provinceData',
						pro: 'cityData',
						city: 'areaData',
						area: 'streetsData',
						street: 'villagesData'
					}
					this[_obj[type]] = res.data
					this.showIndex = arr.indexOf(type)
          this.currentLastLevel = res.data && res.data.length > 0 ? res.data[0].level : 0
					this.isLoading = false
				} else {
					this.isLoading = false
					this.$toast.success(res.msg)
				}
			})
		},
		handleSelectAddress(type, obj) {
			console.log(type, obj)
			switch (type) {
				case 0:
					//选择省
					this.handleGetMap(obj, 'pro')
					this.provinceObj = obj
					this.showIndex = 1
					this.cityData = []
					this.areaData = []
					this.streetsData = []
					this.villagesData = []
					break
				case 1:
					//选择市
					this.handleGetMap(obj, 'city')
					this.cityObj = obj
					this.showIndex = 2
					this.areaData = []
					this.streetsData = []
					this.villagesData = []

					break
				case 2:
					//选择区
					if (this.selectAreaLevelLimit == 3) {
						this.areaObj = obj
					} else {
						this.handleGetMap(obj, 'area')
						this.areaObj = obj
						this.showIndex = 3
						this.streetsData = []
						this.villagesData = []
					}
					break
				case 3:
					//选择街道
					if (this.selectAreaLevelLimit == 4) {
						this.streetObj = obj
					} else {
						this.handleGetMap(obj, 'street')
						this.showIndex = 4
						this.villagesData = []
						this.streetObj = obj
					}
					break
				case 4:
					//选择村、社区
					this.villageObj = obj
					break
				default:
					break
			}
		}
	}
}
</script>

<style lang="less" scoped>
// vant 样式
.van-popup {
	border-radius: 32px 32px 0 0 !important;
}
.page-main {
	z-index: 999;
	background-color: #ffffff;
	border-top: 1px solid rgba(0, 0, 0, 0.2);
	border-radius: 16px 16px 0 0;
	height: 98%;
	.main-operate {
		padding: 0 20px;
		height: 80px;
		line-height: 80px;
		display: flex;
		justify-content: space-between;
		.title-txt {
			color: #343434;
			font-size: 30px;
			&:nth-child(2) {
				color: rgb(64, 158, 255);
			}
		}
	}
	.main-select {
		display: flex;
		justify-content: flex-start;
		color: #343434;
		font-size: 26px;
		height: 80px;
		line-height: 80px;
		margin-left: 20px;
		div:nth-child(1) {
			min-width: 80px;
		}
		div:nth-child(2) {
			min-width: 80px;
		}
		div:nth-child(3) {
			min-width: 80px;
		}
		div {
			display: inline-block;
			padding: 0 10px;
			div-align: center;
			overflow: hidden;
			-webkit-line-clamp: 1;
			div-overflow: ellipsis;
			display: -webkit-box;
			-webkit-box-orient: vertical;
			div-align: center;
		}
		.select {
			font-size: 26px;
			color: #ff4242;
			position: relative;
			&::after {
				content: '';
				width: 100%;
				height: 4px;
				background: #ff4242;
				position: absolute;
				left: 0;
				bottom: 0;
				border-radius: 6px;
			}
		}
	}
	.main-list {
		position: relative;
		overflow-y: auto;
		color: #343434;
		width: 100%;
		height: calc(100% - 160px);
		overflow: auto;
		.list-box {
			display: flex;
			justify-content: flex-start;
			padding-left: 28px;
			height: 80px;
			font-size: 26px;
			line-height: 80px;
		}
		.list-box:last-child {
			border-bottom: none;
		}
		.active {
			color: #ee0a24;
			position: relative;
			&::after {
				content: '';
				width: 30px;
				height: 30px;
				background: url('../assets/images/selectedIcon.png') no-repeat;
				background-size: 100% 100%;
				background-position: center;
				position: absolute;
				right: 28px;
				top: 50%;
				transform: translateY(-50%);
				color: #ee0a24;
			}
		}
	}
}
.select {
  position: relative;
}
.select::after {
  position: absolute;
    box-sizing: border-box;
    content: ' ';
    pointer-events: none;
    right: 0.42667rem;
    bottom: 0;
    left: 0.42667rem;
    border-bottom: 0.02667rem solid #ebedf0;
    -webkit-transform: scaleY(.5);
    transform: scaleY(.5);
}
</style>
